<script setup lang="ts">
import {computed, defineEmits, onMounted, ref, watch} from "vue"
import MenuAPI from "@/api/system/menu";
import RoleAPI from "@/api/system/role";
import useLoading from "@/hooks/loading";

const props = defineProps({
  modelValue: Boolean,
  roleId: [String, Number]
});

const emits = defineEmits<{
  (e: "update:modelValue", t: boolean): void;
}>();

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (newValue) => {
    emits("update:modelValue", newValue);
  },
});

const fieldNames = {
  title: "menu_name",
  key: "id",
  children: "children"
}
const {loading, setLoading} = useLoading();
const treeRef = ref(null)
const treeData = ref([])
const checkedKeys = ref([]);
const checkStrictly = ref(true);

// eslint-disable-next-line consistent-return
const handleAuthDetail = async (roleId: string | number | undefined) => {
  if (!roleId) {
    return false
  }
  try {
    const {data, code} = await RoleAPI.getPerms(roleId);

    if (code === 200 && data) {
      checkedKeys.value = data.menu_ids || [];
    }
  } catch (err) {
    console.warn(err);
    // Message.error("出了点小问题，请稍后重试！");
  }
}

watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      handleAuthDetail(props.roleId)
    }
  },
  {immediate: true}
)

const fetchTableData = async () => {
  setLoading(true)
  try {
    const {data, code} = await MenuAPI.getList({});

    if (code === 200 && data) {
      treeData.value = data || [];
    }
  } catch (err) {
    console.warn(err);
    // Message.error("出了点小问题，请稍后重试！");
  }
  setLoading(false)
}

onMounted(() => {
  fetchTableData()
})

const handleExpand = (check: boolean) => {
  if (treeRef.value) {
    treeRef.value.expandAll(check)
  }
}

const handleSelectAll = (check: boolean) => {
  if (treeRef.value) {
    treeRef.value?.checkAll(check)
  }
}

const handleConfirm = async () => {
  // 获取选中id
  console.log(checkedKeys.value)
  try {
    const {data, code} = await RoleAPI.updatePerms({
      role_id: props.roleId, menu_ids: checkedKeys.value
    });

    if (code === 200 && data) {
      treeData.value = data || [];
    }
  } catch (err) {
    console.warn(err);
    // Message.error("出了点小问题，请稍后重试！");
  }
}
</script>

<template>
  <a-modal
    v-model:visible="dialogVisible"
    width="840px"
    title="权限设置"
    @ok="handleConfirm"
  >
    <div class="main-header">
      <a-space>
        <span>权限</span>
        <a-checkbox @change="handleExpand">展开/折叠</a-checkbox>
        <a-checkbox @change="handleSelectAll">全选/不全选</a-checkbox>
        <a-checkbox v-model="checkStrictly">父子联动</a-checkbox>
      </a-space>
    </div>
    <a-scrollbar type="track" style="height:500px; overflow: auto;">
      <a-spin :loading="loading">
        <a-tree
          ref="treeRef"
          v-model:checked-keys="checkedKeys"
          :checkable="true"
          :check-strictly="checkStrictly"
          :field-names="fieldNames"
          :data="treeData"
        />
      </a-spin>
    </a-scrollbar>
  </a-modal>
</template>

<style scoped lang="less">
.main {
  max-height: 500px;
}
</style>
